import { Modal, Form, Select, Radio, message } from 'antd';
import { useEffect, useState } from 'react';
import ArrayUtils from '@/utils/ArrayUtils';
import { PROJECT_BUG_TYPE, PROJECT_BUG_GROUP, PRIORUTY_LEVEL, PROJECT_BUG_FIX_STATUS } from '@/consts/project'
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect';
import styles from './style.less';
import { RichTextEdit } from '@/components/RichText'
const FormItem = Form.Item;
import { confirm, changeToUser, fix } from '@/services/project/bug'


const BugToUserChangeModal = (props) => {
    const {
        bugDetail,
        onCancel,
        onSuccess,
    } = props;

    const [defaultValues, setDefaultValues] = useState();
    const [modalVisible, setModalVisible] = useState(false);

    useEffect(() => {
        if (bugDetail) {
            setDefaultValues({
                toUserId: bugDetail.toUserId,
                confirmStatus: bugDetail.confirmStatus + "",
            })
            setModalVisible(true)
        }
    }, [bugDetail])

    const onModalCancel = () => {
        setModalVisible(false)
        if (onCancel) {
            onCancel();
        }
    }

    const onChangeSuccess = (data) => {
        setModalVisible(false)
        if (onSuccess) {
            onSuccess()
        }
    }

    const localChangeToUser = (projectId, id, data) => {
        console.log(data)
        if (!data.toUserId && !data.confirmStatus && data.remark?.text === "<p></p>") {
            message.error("您没有变更操作")
            return;
        }

        return changeToUser(projectId, id, data)
    }

    if (!modalVisible) {
        return <></>
    }

    return <BugBaseActionModal
        {...props}
        onSuccess={onChangeSuccess}
        onCancel={onModalCancel}
        doAction={localChangeToUser}
        visible={modalVisible}
        enableKeys={["toUserId", "confirmStatus", "remark"]}
        defaultValues={defaultValues}></BugBaseActionModal>
}

const BugConfirmModal = (props) => {
    const {
        bugDetail,
        onCancel,
        onSuccess,
    } = props;

    const [defaultValues, setDefaultValues] = useState();
    const [modalVisible, setModalVisible] = useState(false);

    useEffect(() => {
        if (bugDetail) {
            setDefaultValues({
                toUserId: bugDetail.toUserId,
                groupName: bugDetail.groupName,
                type: bugDetail.type + "",
                priorityLevel: bugDetail.priorityLevel + ""
            })
            setModalVisible(true)
        }
    }, [bugDetail])

    const onModalCancel = () => {
        setModalVisible(false)
        if (onCancel) {
            onCancel();
        }
    }

    const onChangeSuccess = (data) => {
        setModalVisible(false)
        if (onSuccess) {
            onSuccess()
        }
    }



    if (!modalVisible || !defaultValues || !bugDetail) {
        return <></>;
    }

    return <BugBaseActionModal
        {...props}
        onSuccess={onChangeSuccess}
        onCancel={onModalCancel}
        visible={modalVisible}
        doAction={confirm}
        enableKeys={["toUserId", "groupName", "type", "priorityLevel", "remark"]}
        defaultValues={defaultValues}></BugBaseActionModal>

}



const BugFixModal = (props) => {
    const {
        bugDetail,
        myInfo,
        onCancel,
        onSuccess,
    } = props;

    const [defaultValues, setDefaultValues] = useState();
    const [modalVisible, setModalVisible] = useState(false);

    useEffect(() => {
        if (bugDetail) {
            setDefaultValues({
                toUserId: bugDetail.userId,
                groupName: bugDetail.groupName,
                type: bugDetail.type + "",
                fixUserId: myInfo?.id,
                fixStatus: "2",
            })
            setModalVisible(true)
        }

    }, [bugDetail])

    const onModalCancel = () => {
        setModalVisible(false)
        if (onCancel) {
            onCancel();
        }
    }

    const onChangeSuccess = (data) => {
        setModalVisible(false)
        if (onSuccess) {
            onSuccess()
        }
    }

    const localFix = (projectId, id, data) => {
        if (!data.fixStatus) {
            data.fixStatus = data.fixStatus || "2";
            data.oldData = {
                fixStatus : bugDetail.fixStatus
            }
        }
        return fix(projectId, id, data)
    }

    if (!modalVisible || !defaultValues || !bugDetail) {
        return <></>;
    }

    return <BugBaseActionModal
        {...props}
        onSuccess={onChangeSuccess}
        onCancel={onModalCancel}
        visible={modalVisible}
        doAction={localFix}
        enableKeys={["fixUserId", "fixStatus", "toUserId", "groupName", "type", "remark"]}
        defaultValues={defaultValues}></BugBaseActionModal>

}

const BugBaseActionModal = (props) => {
    const {
        visible,
        title,
        bugDetail,
        onSuccess,
        onCancel,
        defaultValues,
        enableKeys = [],
        doAction
    } = props;

    const [modalVisible, setModalVisible] = useState(false);
    const [form] = Form.useForm();
    const [defaultForm, setDefaultForm] = useState();
    const [finalValues, setFinalValues] = useState({});
    const [submitLoading, setSubmitLoading] = useState(false)

    useEffect(() => {
        if (visible) {
            setFinalValues({})
            setDefaultForm(defaultValues)
            setModalVisible(visible)
        }
    }, [defaultValues, visible])

    const onModalCancel = () => {
        setModalVisible(false);
        if (onCancel) {
            onCancel()
        }
    }

    const onSaveSuccess = () => {
        if (onSuccess) {
            onSuccess()
        }
    }

    const onValueChange = (value) => {
        let payload = finalValues.payload || {}
        if (value.payload) {
            if (payload) {
                payload = {
                    ...payload,
                    ...value.payload
                }
            }
        }

        setFinalValues({
            ...finalValues,
            ...value,
            payload: payload
        })
    }

    const submit = async () => {
        await form.validateFields();
        setSubmitLoading(true)
        let keys = Object.keys(finalValues);
        const data = {
            ...finalValues
        }
        let oldData = {};
        for (let index in keys) {
            let key = keys[index];
            if (data[key] === bugDetail[key] || data[key] + "" === bugDetail[key] + "") {
                delete data[key];
            } else {
                oldData[key] = bugDetail[key];
                if (key === "toUserId") {
                    oldData.payload = oldData.payload || {}
                    oldData.payload.toUserId = bugDetail.toUser?.nickName
                }
                if (key === "fixUserId") {
                    oldData.payload = oldData.payload || {}
                    oldData.payload.fixUserId = bugDetail.fixUser?.nickName
                }
            }
        }
        data.oldData = oldData;
        let primise = doAction(bugDetail.projectId, bugDetail.id, data)
        if (primise) {
            primise.then((result) => {
                if (result?.success) {
                    onSaveSuccess(data)
                    setSubmitLoading(false)
                }
            })
        }
    }


    return <Modal
        visible={modalVisible}
        title={title}
        closable={true}
        width="80%"
        title={bugDetail.name}
        onCancel={onModalCancel}
        onOk={submit}
        submitLoading={submitLoading}
    >
        <Form
            form={form}
            preserve={false}
            labelAlign="right"
            initialValues={defaultForm}
            onValuesChange={onValueChange}
        >
            {enableKeys.indexOf("toUserId") > -1 &&
                <FormItem
                    name="toUserId"
                    label="指派给"
                    rules={[
                        {
                            required: true,
                            message: "指派给",
                        },
                    ]}
                >
                    <EnterpriseUserSelect
                        onChange={(userId, user) => {
                            onValueChange({
                                toUserId: userId,
                                payload: {
                                    toUserId: user.nickName
                                }
                            })
                        }}
                        projectId={bugDetail?.projectId} ></EnterpriseUserSelect>
                </FormItem>
            }
            {enableKeys.indexOf("fixUserId") > -1 &&
                <FormItem
                    name="fixUserId"
                    label="解决人"
                    rules={[
                        {
                            required: true,
                            message: "解决人",
                        },
                    ]}
                >
                    <EnterpriseUserSelect
                        onChange={(userId, user) => {
                            onValueChange({
                                fixUserId: userId,
                                payload: {
                                    fixUserId: user.nickName
                                }
                            })
                        }}
                        projectId={bugDetail?.projectId} ></EnterpriseUserSelect>
                </FormItem>
            }
            {enableKeys.indexOf("fixStatus") > -1 &&
                <FormItem
                    name="fixStatus"
                    label="解决状态"
                    rules={[
                        {
                            required: true,
                            message: "解决状态",
                        },
                    ]}
                >
                    <Select placeholder={"请选择解决状态"}>
                        {ArrayUtils.jsonToArray(PROJECT_BUG_FIX_STATUS).filter((item) => item.key !== "0").map(item => <Option value={`${item.key}`} key={`${item.key}`}>{item.value.name}</Option>)}
                    </Select>
                </FormItem>
            }
            {enableKeys.indexOf("confirmStatus") > -1 &&
                <FormItem
                    name="confirmStatus"
                    label="确认状态"
                    rules={[
                        {
                            required: true,
                            message: "确认状态",
                        },
                    ]}
                >
                    <Radio.Group options={[
                        { label: '否', value: '0' },
                        { label: '是', value: '1' }
                    ]} />
                </FormItem>
            }

            {enableKeys.indexOf("groupName") > -1 &&
                <FormItem
                    name="groupName"
                    label="bug归属"
                    rules={[
                        {
                            required: true,
                            message: "请选择归属",
                        },
                    ]}
                >
                    <Select placeholder={"请选择bug归属"}>
                        {ArrayUtils.jsonToArray(PROJECT_BUG_GROUP).map(item => <Option value={`${item.key}`} key={`${item.key}`}>{item.value.name}</Option>)}
                    </Select>
                </FormItem>
            }
            {enableKeys.indexOf("type") > -1 &&

                <FormItem
                    name="type"
                    label="bug类型"
                    rules={[
                        {
                            required: true,
                            message: "请选择类型",
                        },
                    ]}
                >
                    <Select placeholder={"请选择bug类型"}>
                        {ArrayUtils.jsonToArray(PROJECT_BUG_TYPE).map(item => <Option value={`${item.key}`} key={`${item.key}`}>{item.value.name}</Option>)}
                    </Select>
                </FormItem>
            }
            {enableKeys.indexOf("priorityLevel") > -1 &&

                <FormItem
                    name="priorityLevel"
                    label="优先级"
                    rules={[
                        {
                            required: true,
                            message: "请选择优先级",
                        },
                    ]}
                >
                    <Select>
                        {ArrayUtils.jsonToArray(PRIORUTY_LEVEL).map(item => <Option value={`${item.key}`} key={`${item.key}`}>{item.value.name}</Option>)}
                    </Select>
                </FormItem>
            }
            {enableKeys.indexOf("remark") > -1 &&

                <FormItem label={"备注"}
                    name={["remark"]}
                >
                    <RichTextEdit
                        onChange={(value) => {
                            onValueChange({
                                remark: {
                                    text: value?.text
                                }
                            })
                        }}
                        showFormButton={false} size="small" />
                </FormItem>
            }
        </Form>
    </Modal>
}

export { BugConfirmModal, BugToUserChangeModal, BugFixModal }